const { whenProd } = require('@craco/craco')
const path = require('path')
const TerserPlugin = require('terser-webpack-plugin')
const CompressionPlugin = require('compression-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin // 添加打包分析
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const ESLintWebpackPlugin = require('eslint-webpack-plugin')
const os = require('os')
const autoprefixer = require('autoprefixer')
const threads = os.cpus().length

module.exports = {
  style: {
    postcss: {
      plugins: [
        new autoprefixer()
      ]
    },
  },
  webpack: {
    plugins: [
      ...whenProd(() => [ // 生产环境下plugin的配置
        new TerserPlugin({
          terserOptions: {
            compress: {
              drop_console: process.env.NODE_ENV === 'production'
            }
          }
        }),

        new CompressionPlugin({
          algorithm: 'gzip', // 使用gzip压缩
          test: /\.js(\?.*)?$/i, // 压缩js文件
          threshold: 10240, // 只有大于10240字节的文件会被压缩
          minRatio: 0.8, // 压缩率达到0.8才会被应用
          deleteOriginalAssets: false, // 是否删除原文件
        }),

        new BundleAnalyzerPlugin() // 打包的时候 才显示打包分析
      ], [])
    ],

    // 要在tsconfig.json里面同步配置
    // "baseUrl": ".",   "paths": {"@/*": ["src/*"], "@/assets*": ["src/assets/*"]}
    alias: {
      "@": path.resolve(__dirname, 'src')
    },

    configure: (webpackConfig) => {
      webpackConfig.devtool = false
      webpackConfig.output.filename = 'js/[name].[chunkhash:3].js'
      webpackConfig.output.chunkFilename = 'js/[name].[chunkhash:3].js'
      webpackConfig.module.rules[1].oneOf[3].options.plugins.push('@babel/plugin-transform-runtime') //减少babel体积
      webpackConfig.module.rules[1].oneOf[1].generator = {filename: 'image/[name].[contenthash:2][ext]'} 

      // 使用cnpm i image-webpack-loader安装  如果使用npm安装 有些依赖不能下载 就会报错
      // 比如说Error: Cannot find module 'imagemin-gifsicle' 压缩图片
      webpackConfig.module.rules[1].oneOf[1].use = [{
        loader: 'image-webpack-loader',
        options: {
          mozjpeg: { progressive: true, quality: 65},
          optipng: { enabled: false },
          pngquant: { quality: [0.65, 0.90],speed: 4 },
          gifsicle: { interlaced: false}
        }  
      }]

      // 'Cookies': 'js-cookie' 前面的key是 文件中引入的名字, 后面的value是package.json中下载对应的名字
      webpackConfig.externals = {
        ...webpackConfig.externals,
        'axios': 'axios',
        'Cookies': 'js-cookie',
        'React': 'react',
        'ReactDOM': 'react-dom'
      }

      webpackConfig.plugins.map((plugin) => {
        whenProd(() => {
          if(plugin instanceof MiniCssExtractPlugin) {
            plugin.options.filename = 'css/[name].[contenthash:3].css'  
          } else if(plugin instanceof ESLintWebpackPlugin) {
            plugin.threads = threads
          }
        })
        return plugin
      })

      webpackConfig.optimization = {
        splitChunks: {
          cacheGroups: {
            axios: {
              name: 'axios',
              test: /[\\/]node_modules[\\/]axios[\\/]/,
              chunks: 'all',
              minSize: 0,
              minChunks: 1,
              priority: 5
            }
          }
        },

        runtimeChunk: {
          name: (entrypoint) => `runtime-${entrypoint.name}.js`
        }
      }

      return webpackConfig
    }
  } 
}